import {
	FormControl,
	FormHelperText,
	InputLabel,
	MenuItem,
	Select,
	type SelectProps
} from '@mui/material'
import { useId } from 'react'
import { type Control, Controller } from 'react-hook-form'

export const SelectFieldControlled = (
	props: Partial<Omit<SelectProps, 'variant'>> & {
		control: Control<any>
		name: string
		label: string
		options: { id: number; name: string }[]
	}
) => {
	const { control, name, label, options, ...rest } = props
	const idForLabel = useId()

	return (
		<Controller
			name={name}
			control={control}
			render={({ field, fieldState }) => (
				<FormControl error={!!fieldState.error}>
					<InputLabel id={idForLabel}>{label}</InputLabel>
					<Select
						{...field}
						{...rest}
						labelId={idForLabel}
						label={label}
						variant='outlined'
					>
						{options.map(option => (
							<MenuItem
								key={option.id}
								value={option.id}
							>
								{option.name}
							</MenuItem>
						))}
					</Select>
					{fieldState.error && (
						<FormHelperText>{fieldState.error.message}</FormHelperText>
					)}
				</FormControl>
			)}
		/>
	)
}
